import Vue from "vue";
import Home from "./Home.vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);
//把全局的js跳转路由，重复进入报错给干掉
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch((err) => err);
};

const router = new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/home",
      component: Home,
    },
    {
      path: "/different",
      component: () => import("./Different.vue"),
    },
    {
      path: "/car",
      component: () => import("./Car.vue"),
    },
    {
      path: "/user",
      component: () => import("./User.vue"),
    },
    {
      path: "/detail",
      component: () => import("./Detail.vue"),
    },
    {
      path: "/login",
      component: () => import("./Login.vue"),
    },
    {
      path: "/",
      redirect: "/home",
    },
  ],
});
router.beforeEach((to, from, next) => {
  let isLogin;
  if (!window.sessionStorage.getItem("vuex")) {
    isLogin = false;
  }
  isLogin = JSON.parse(window.sessionStorage.getItem("vuex"));
  if (to.path == "/detail" && !isLogin) {
    return next("/login");
  }
  console.log(isLogin);
  if (to.path == "/login" && isLogin) {
    if (from.path == "/home" || from.path == "/") {
      console.log(1);
      return;
    }
    return next(false);
  }

  next();
});

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

export default router;
